package com.lzj.server.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lzj.server.common.model.Attachment;
import com.lzj.server.constant.enums.VideoStatusEnum;
import com.lzj.server.entity.video.VideoLibrary;
import com.lzj.server.repository.mapper.AttachmentMapper;
import com.lzj.server.repository.mapper.VideoMapper;
import com.lzj.server.service.VideoService;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

/**
 * @author Lzj
 * @date 2025/5/26
 * @description
 */
@Service
public class VideoServiceImpl extends ServiceImpl<VideoMapper, VideoLibrary> implements VideoService {

    @Resource
    private VideoMapper videoMapper;

    @Resource
    private AttachmentMapper attachmentMapper;

    /**
     * 新增或编辑视频
     *
     * @param video 视频信息
     * @return boolean
     */
    @Override
    public Boolean addOrEdit(VideoLibrary video) {
        Assert.isTrue(video != null, "视频信息不能为空");
        Long id = video.getId();
        boolean isFlag = false;
        if (ObjectUtils.isEmpty(id)) {
            // 新增视频
            // 1. 初始化视频信息
            video.setAuditStatus(VideoStatusEnum.INVALID.code());
            video.setViewCount(0L);
            video.setFavoriteCount(0L);
            video.setCommentCount(0L);
            video.setVisibility(ObjectUtils.defaultIfNull(video.getVisibility(), 0));
            video.setDescription(StringUtils.defaultIfEmpty(video.getDescription(), "还没有相关描述"));
            // 2. 获取附件信息
            Attachment attach = attachmentMapper.selectById(video.getVideoAttachmentId());
            video.setDuration(attach.getDuration());
            // 3. 保存视频信息
            isFlag = videoMapper.insert(video) > 0;
        } else {
            // 编辑视频
            VideoLibrary v = videoMapper.selectById(id);
            Assert.isTrue(v != null, "所编辑的视频不存在");
            BeanUtil.copyProperties(video, v, CopyOptions.create().setIgnoreNullValue(true));
            isFlag = videoMapper.updateById(v) > 0;
        }
        return isFlag;
    }

    /**
     * 观看权限判断
     *
     * @param id 视频id
     * @return booelan
     */
    @Override
    public Boolean hasViewPermission(Long id) {
        // 获取视频需要的权限

        return true;
    }

    @Override
    public IPage<VideoLibrary> getPageBean(IPage<VideoLibrary> page, VideoLibrary video) {
        // TODO 实现分页查询
        Assert.isTrue(video == null, "分页信息不能为空");
        Long categoryId = video.getCategoryId();
        String title = video.getTitle();
        Integer visibility = video.getVisibility();
        return videoMapper.selectPage(page, null);
    }
}
